import {
	createRouter,
	createWebHistory
} from 'vue-router'
import {
	isArray,
	isObject
} from '@/utils/object.js'

import RouteAuthentication from '@/plugin/RouteAuthentication.js'

const routes = []

//获取与当前文件RouterIndex.js同级的所有js文件
const routerFiles = require.context('./', false, /\.js$/)

routerFiles.keys().forEach(path => {
	// ./abc.js => abc
	let fileName = path.replace(/(.*\/)*([^.]+).*/ig, "$2")
	if (path === './RouterIndex.js') {
		//跳过自身
		return
	}
	let exportModels = routerFiles(path)
	let route = exportModels.default
	if (typeof route === 'undefined') {
		//如果文件中没有export default，那就把所有的export当成单页面
		for (let route in exportModels) {
			if (isObject(exportModels[route])) {
				routes.push(exportModels[route])
			} else {
				console.error("无法识别的路由项", exportModels[route])
			}
		}
	} else {
		if (isArray(route)) {
			console.log(route)
			//是数组，就把这路由当成多页面
			let component = routerFiles(path).component
			if (typeof component !== 'object' || typeof component !== 'function') {
				component = () => import('@/views/RouterView.vue')
			}
			routes.push({
				path: `/${fileName}`,
				children: route,
				component
			})
		} else if (isObject(route)) {
			//是object，就把这路由当成单页面
			routes.push(route)
		} else {
			console.error("无法识别的路由项", route)
		}
	}
})


const router = createRouter({
	history: createWebHistory(process.env.BASE_URL),
	routes
})
let rs = router.getRoutes()
console.log(`生成了${rs.length}个路由映射`, rs)
console.log(routes)

function Authentication(to, from, next) {
	let flag = true
	for (let r of to.matched) {
		if (to.name !== undefined && to.name !== null &&r.components&& r.components.default.name === to.name || r.components
			.default.name === 'component') {
			flag = false
			break
		}
	}
	if (flag) {
		console.warn("路由的name需要和组件的name保持一致且不为空", to,"路由名",to.name,"组件名",to.matched[0]?.components.default.name)
	}
	RouteAuthentication(to, next, () => {
		next('/404?path=' + to.fullPath)
	}, () => {
		next('/404?path=' + to.fullPath)
	})
}

router.beforeEach(Authentication)

export default router
